/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.je.bpm.common.operation.OperatorEnum;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.SequenceFlow;
import com.je.bpm.core.model.config.CustomEvent;
import com.je.bpm.core.model.event.StartEvent;
import com.je.bpm.core.model.process.Process;
import com.je.bpm.core.model.task.KaiteBaseUserTask;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.delegate.DelegateHelper;
import com.je.bpm.engine.impl.bpmn.behavior.KaiteBaseUserTaskActivityBehavior;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.identity.Authentication;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.deploy.DeploymentManager;
import com.je.bpm.engine.impl.runtime.ProcessInstanceBuilderImpl;
import com.je.bpm.engine.impl.util.ProcessDefinitionRetriever;
import com.je.bpm.engine.impl.util.ProcessInstanceHelper;
import com.je.bpm.engine.repository.ProcessDefinition;
import com.je.bpm.engine.runtime.ProcessInstance;
import com.je.bpm.runtime.shared.operator.AudflagEnum;
import com.je.common.auth.AuthAccount;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发起命令
 */
public class SponsorProcessInstanceCmd<T> implements Command<ProcessInstance>, Serializable {

    private static final long serialVersionUID = 1L;
    protected String processDefinitionKey;
    protected String processDefinitionId;
    protected Map<String, Object> variables;
    protected Map<String, Object> transientVariables;
    protected String businessKey;
    protected String tenantId;
    protected String processInstanceName;
    protected String firstUser;
    protected String assignee;
    protected ProcessInstanceHelper processInstanceHelper;
    protected String secondTaskRef;
    protected Map<String, Object> bean;
    protected String prod;
    protected String comment;
    protected String sequentials;
    protected String isJump;


    public SponsorProcessInstanceCmd(String processDefinitionKey, String processDefinitionId, String businessKey, String firstUser, String assignee, Map<String, Object> variables) {
        this.processDefinitionKey = processDefinitionKey;
        this.processDefinitionId = processDefinitionId;
        this.businessKey = businessKey;
        this.variables = variables;
        this.firstUser = firstUser;
        this.assignee = assignee;
    }

    public SponsorProcessInstanceCmd(String processDefinitionKey, String processDefinitionId, String businessKey, String assignee, Map<String, Object> variables) {
        this.processDefinitionKey = processDefinitionKey;
        this.processDefinitionId = processDefinitionId;
        this.businessKey = businessKey;
        this.variables = variables;
        this.assignee = assignee;
    }

    public SponsorProcessInstanceCmd(String processDefinitionKey, String processDefinitionId, String businessKey, String firstUser, String assignee, Map<String, Object> variables, String tenantId) {
        this(processDefinitionKey, processDefinitionId, businessKey, firstUser, assignee, variables);
        this.tenantId = tenantId;
    }

    public SponsorProcessInstanceCmd(String processDefinitionKey, String processDefinitionId, String businessKey, String assignee, Map<String, Object> variables, String tenantId) {
        this(processDefinitionKey, processDefinitionId, businessKey, assignee, variables);
        this.tenantId = tenantId;
    }

    public SponsorProcessInstanceCmd(String processDefinitionId, String assignee, String secondTaskRef, String prod, String businessKey,
                                     String tenantId, Map<String, Object> bean, String comment, String sequentials, String isJump) {
        this.processDefinitionId = processDefinitionId;
        this.businessKey = businessKey;
        this.tenantId = tenantId;
        this.assignee = assignee;
        this.secondTaskRef = secondTaskRef;
        this.bean = bean;
        this.prod = prod;
        this.comment = comment;
        this.sequentials = sequentials;
        this.isJump = isJump;
    }

    public SponsorProcessInstanceCmd(ProcessInstanceBuilderImpl processInstanceBuilder) {
        this(processInstanceBuilder.getProcessDefinitionKey(),
                processInstanceBuilder.getProcessDefinitionId(),
                processInstanceBuilder.getBusinessKey(),
                processInstanceBuilder.getFirstUser(),
                processInstanceBuilder.getAssigneeList(),
                processInstanceBuilder.getVariables(),
                processInstanceBuilder.getTenantId());
        this.processInstanceName = processInstanceBuilder.getProcessInstanceName();
        this.transientVariables = processInstanceBuilder.getTransientVariables();
    }

    @Override
    public ProcessInstance execute(CommandContext commandContext) {
        commandContext.addAttribute(CommandContext.BEAN, bean);
        commandContext.addAttribute(CommandContext.PROD, prod);
        processInstanceHelper = commandContext.getProcessEngineConfiguration().getProcessInstanceHelper();
        DeploymentManager deploymentCache = commandContext.getProcessEngineConfiguration().getDeploymentManager();

        ProcessDefinitionRetriever processRetriever = new ProcessDefinitionRetriever(this.tenantId, deploymentCache);
        ProcessDefinition processDefinition = processRetriever.getProcessDefinition(this.processDefinitionId, this.processDefinitionKey);

        //找到第一个和第二个节点的id
        BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(processDefinition.getId());
        Process mainProcess = bpmnModel.getMainProcess();
        StartEvent startEvent = (StartEvent) mainProcess.getInitialFlowElement();
        String firstTaskRef = startEvent.getOutgoingFlows().get(0).getTargetRef();
        //找到第一个任务节点
        KaiteBaseUserTask firstBaseUserTask = (KaiteBaseUserTask) bpmnModel.getFlowElement(firstTaskRef);
        if (!(firstBaseUserTask instanceof KaiteBaseUserTask)) {
            throw new ActivitiException("Sponsor process only effective on the first task is KaiteUserTask.");
        }

        String firstTaskId = firstBaseUserTask.getId();
        String firstTaskName = firstBaseUserTask.getName();

        if (variables == null) {
            variables = new HashMap<>();
        }

        if (StringUtils.isEmpty(firstUser)) {
            AuthAccount activitiUser = Authentication.getAuthenticatedUser();
            if (activitiUser == null) {
                throw new ActivitiException("Can not get logined user from the context.");
            }
            firstUser = activitiUser.getDeptId();
        }

        if (transientVariables == null) {
            transientVariables = new HashMap<>();
        }

        //是否是跳跃
        commandContext.addAttribute(commandContext.IS_JUMP, isJump);
        String targetNodeId = "";
        List<FlowElement> flowElementList = bpmnModel.getMainProcess().getFlowElementList();
        for (FlowElement flowElement : flowElementList) {
            if (flowElement instanceof SequenceFlow) {
                if (flowElement.getId().equals(secondTaskRef)) {
                    targetNodeId = ((SequenceFlow) flowElement).getTargetRef();
                }
            }
        }
        //跳跃的目标节点
        commandContext.addAttribute(CommandContext.JUMP_TARGET_NODE_ID, targetNodeId);

        //设置发起变量
        commandContext.addAttribute(CommandContext.IS_SPONSOR, true);
        commandContext.addAttribute(commandContext.COMMENT, comment);
        transientVariables.put(KaiteBaseUserTaskActivityBehavior.PREV_ASSIGNEE, Authentication.getAuthenticatedUser().getDeptId());
        transientVariables.put(KaiteBaseUserTaskActivityBehavior.DIRECT_TASK_ID, firstTaskId);
        transientVariables.put(KaiteBaseUserTaskActivityBehavior.DIRECT_TASK_NAME, firstTaskName);
        transientVariables.put(KaiteBaseUserTaskActivityBehavior.DIRECT_TASK_TARGET, secondTaskRef);
        transientVariables.put(KaiteBaseUserTaskActivityBehavior.SEQUENTIALS, sequentials);
        //设置指派人变量
        transientVariables.put(firstTaskId, firstUser);
        //如果是可跳跃 目标节点不一定是下个节点
        if (!isJump.equals("1")) {
            transientVariables.put("outgoing", secondTaskRef);
        } else {
            transientVariables.put("outgoing", "");
            commandContext.addAttribute(CommandContext.BEAN, bean);
        }
        //添加审批告知变量
        Context.getCommandContext().getProcessEngineConfiguration().getProcessInstanceHelper()
                .addApprovalNotificationVariable(bpmnModel, firstTaskId, comment, SubmitTypeEnum.SPONSOR.getName());
        Context.getCommandContext().addAttribute(KaiteBaseUserTaskActivityBehavior.UPCOMINGINFO,
                DelegateHelper.buildUpcomingInfo(bean, comment, SubmitTypeEnum.SPONSOR, businessKey, "", null,
                        JSONArray.parseArray(assignee).toJSONString()));
        JSONArray assigneeUsers = JSONArray.parseArray(assignee);
        if (assigneeUsers != null) {
            for (Object user : assigneeUsers) {
                JSONObject userJson = (JSONObject) JSONObject.parse(String.valueOf(user));
                transientVariables.put(userJson.getString("nodeId"), userJson.getString("assignee"));
                transientVariables.put(userJson.getString("nodeId"), userJson.getString("assignee"));
            }
        }
        ProcessInstance processInstance = createAndStartProcessInstance(processDefinition, businessKey, processInstanceName, variables, transientVariables);

        processInstanceHelper.buildStartBeanInfo(bean);
        //执行自定义流程、节点策略
        commandContext.getProcessEngineConfiguration().getProcessInstanceHelper().invokeEvent
                (mainProcess.getCustomEventListeners(), firstBaseUserTask.getName(),
                        firstBaseUserTask.getId(), firstBaseUserTask.getIncomingFlows().get(0).getId(),
                        CustomEvent.CustomEventEnum.PROCESS_START, commandContext, comment, "", OperatorEnum.PROCESS_EMPTY_START_OPERATOR);
        bean = commandContext.getBean();
        bean.put("SY_PDID", processInstance.getProcessDefinitionId());
        bean.put("SY_PIID", processInstance.getProcessInstanceId());
        bean.put("SY_AUDFLAG", AudflagEnum.WAIT.toString());
        commandContext.updateBean(bean, businessKey, bpmnModel.getMainProcess().getProcessConfig());
        return processInstance;
    }

    protected ProcessInstance createAndStartProcessInstance(ProcessDefinition processDefinition, String businessKey, String processInstanceName, Map<String, Object> variables, Map<String, Object> transientVariables) {
        return processInstanceHelper.createAndStartProcessInstance(processDefinition, businessKey, processInstanceName, variables, transientVariables);
    }


}
